package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.*;
import com.sky.result.Result;
import com.sky.service.OrderSubmitService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;


@Service
public class OrderSubmitServiceImpl implements OrderSubmitService {
    @Autowired
    private OrderSubmitMapper orderSubmitMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;


    // 生成订单号：时间戳（yyyyMMddHHmmssSSS）+ 3位随机数
    public static String generateOrderNo() {
        // 1. 时间戳部分（精确到毫秒，确保趋势递增）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String timeStr = sdf.format(new Date());

        // 2. 随机数部分（避免同一毫秒内重复）
        Random random = new Random();
        int randomNum = random.nextInt(900) + 100; // 生成100-999的随机数

        // 3. 拼接订单号
        return timeStr + randomNum;
    }

    @Override
    @Transactional
    public Result submit(OrdersSubmitDTO ordersSubmitDTO) {
        Orders orders = new Orders();

        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setNumber(OrderSubmitServiceImpl.generateOrderNo());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        //判断购物车数据和地址是否为空
        if(ordersSubmitDTO.getAddressBookId() == null || ordersSubmitDTO.getAddressBookId() == 0){
            throw new RuntimeException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //通过地址查询收货人信息
        AddressBook addressBook =addressBookMapper.getById(orders.getAddressBookId());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        //通过用户id查询用户信息
        orders.setUserName(userMapper.getById(BaseContext.getCurrentId()));
        //插入订单表
         orderSubmitMapper.insert(orders);
        //插入订单详情表
        //获取购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.select(BaseContext.getCurrentId());
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();

            orderDetail.setOrderId(orders.getId());
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setAmount(shoppingCart.getAmount());

            // 将订单详情添加到列表中
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatchs(orderDetailList);

        return Result.success();



    }
}
